package com.goblin.model.media.controller;

import com.goblin.common.response.PageHelper;
import com.goblin.common.response.Paged;
import com.goblin.common.response.ParamException;
import com.goblin.common.response.Response;
import com.goblin.model.base.BaseController;
import com.goblin.model.media.po.Chat;
import com.goblin.model.media.po.Message;
import com.goblin.model.media.service.MessageService;
import com.goblin.model.socket.SocketServer;
import com.goblin.model.uaa.po.User;
import com.goblin.security.AuthorityStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/v1/media/chat/relation")
public class ChatController extends BaseController<Chat> {

    @Autowired
    private MessageService messageService;

    @Resource(name = "defaultThreadPool")
    private ThreadPoolTaskExecutor executor;


    @GetMapping("/relations")
    public Response<Paged<Chat>> paged(PageHelper pageable) {
        String authorization = request.getHeader("authorization");
        List info = AuthorityStore.getAuth(authorization);
        User user = (User) info.get(1);
        Paged<Chat> entities = this.messageService.pagedChat(user.getId(), pageable);
        return Response.success(entities);
    }

    @PostMapping("/sendMsg")
    public Response sendOnlineMsg(@RequestBody List<Integer> ids, @RequestParam Integer type) {
        String authorization = request.getHeader("authorization");
        List info = AuthorityStore.getAuth(authorization);
        User user = (User) info.get(1);

        this.executor.submit(() -> {
            ids.forEach((e) -> {
                Message m = new Message();
                m.setReceive(false);
                m.setType(type); //上线消息
                m.setUserFrom(user);
                try {
                    SocketServer.sendMessage(m, e);
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
            });
        });
        return Response.success();
    }

    @Override
    public void before(Chat chat) {
        super.before(chat);

        if (chat.getCustomA() == null || chat.getCustomA().getId() == null || chat.getCustomB() == null || chat.getCustomB().getId() == null) {
            throw new ParamException("对话人信息不能为空");
        }

        List<Chat> list = this.messageService.findChatByCustomA(chat.getCustomA());
        list.forEach((e) -> {
            if (e.getCustomB().getId() == chat.getCustomB().getId() && e.getDeleteTime() == null) {
                throw new ParamException("该对话当前已存在");
            }
        });

        chat.setDate(System.currentTimeMillis());
    }

}
